<template>
  <page-lr class="page-air-quality-calendar">
      <el-form size="small" :model="searchForm" label-width="90px" slot="content-right">
        <el-form-item label="选择月份：">
          <el-date-picker v-model="searchForm.month_str" type="month" value-format="yyyy-MM" placeholder="选择月份" @change="getList"></el-date-picker>
        </el-form-item>
        <el-form-item label="污染指标：">
          <el-button v-for="(item,index) in legend.list" :key="index" size="small" :type="legend.type == item.name ? 'primary' : 'default'" @click="changeType(item.name)">
            {{ item.name }}
          </el-button>
        </el-form-item>
      </el-form>
    <div class="" slot="content-left" style="width:100%;display:flex;">
      <div class="list-year">
        <v-chart :options="option" autoresize :style="{height:domHeight,width:'100%'}"></v-chart>
      </div>
      <div class="legend-box">
        <div class="top">
          <h2>{{ legend.type }}</h2>
          <div v-for="(item,index) in legend.typeList" :key="index" :class="'item item-'+item.id">
              <div class="name">{{ item.name.substring(0,2) }}</div>
              <div :class="'column column-'+item.id"></div>
              <div class="value">{{ item.value }}</div>
          </div>
        </div>

        <ul class="list-type">
          <li v-for="(item,index) in typeList" :key="index" :class="'dot dot-'+(index+1)">
            <span>{{item.name.substring(0,2)}}：{{getTotal(item.name)}}</span>
          </li>
        </ul>
      </div>
    </div>
  </page-lr>
</template>
<script>
import {city} from '@/config/env';
export default {
  data() {
    return {
      searchForm:{
        month_str: '2023-05'
      },
      typeList:[
        {id:1,name: '优', value: 0, },
        {id:2,name: '良', value: 0, },
        {id:3,name: '轻度污染', value: 0, },
        {id:4,name: '中度污染', value: 0, },
        {id:5,name: '重度污染', value: 0, },
        {id:6,name: '严重污染', value: 0, },
      ],
      legend:{
        type: 'AQI',
        typeId: 'aqi',
        index: 0,
        list:[
          {id: 'aqi', name: 'AQI', values: [0,50,100,150,200,300]},
          {id: 'pm25', name: 'PM₂.₅', values: [0,35,75,115,150,250]},
          {id: 'pm10', name: 'PM₁₀', values: [0,50,150,250,350,420]},
          {id: 'so2', name: 'SO₂', values: [0,50,150,475,800,1600]},
          {id: 'no2', name: 'NO₂', values: [0,40,80,180,280,565]},
          {id: 'co', name: 'CO', values: [0,2,4,35,14,24]},
          {id: 'o3_8h', name: 'O₃_8h', values: [0,100,160,215,265,800]},
        ],
        typeList:[],
      },
      list: [],
      option: {},
      colors : {
        优: 'rgb(0, 228, 0)',
        良: 'rgb(255, 255, 0)',
        轻度污染: 'rgb(255, 126, 0)',
        中度污染: 'rgb(255, 0, 0)',
        重度污染: 'rgb(153, 0, 76)',
        严重污染: 'rgb(126, 0, 35)'
      },
      levels : ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染'],
      levelValues:{
        aqi: [50, 100, 150, 200, 300],
        pm25: [35, 75, 115, 150, 250],
        pm10: [50, 150, 250, 350, 420],
        so2: [50, 150, 475, 800, 1600],
        no2: [40, 80, 180, 280, 565],
        co: [2, 4, 35, 14, 24, 36],
        o3_8h: [100, 160, 215, 265, 800],
      },
      domHeight: '',
    }
  },
  created() {
    let height = document.body.clientHeight - 64 - 40 - 48*2 - 20;
    height = height > 600 ? height : 600;
    this.domHeight = height + 'px';
    this.searchForm.month_str = this.$moment().format('YYYY-MM');
    this.legend.typeList = JSON.parse(JSON.stringify(this.typeList));
    this.getList();
  },
  methods: {
    getList(){
      this.$request('get', '/chaqi/station_month', this.searchForm, (data,msg) => {
        this.list = data;
        this.changeType('AQI')
      })
    },
    changeType(val){      
      // this.legend.typeList = JSON.parse(JSON.stringify(this.typeList));
      this.legend.type = val;
      let i,list;
      this.legend.list.forEach((item,index) => {
        if(item.name == val){
          i = index;
          this.legend.index = index;
          this.legend.typeId = item.id;
          list = item.values;
        }
      });
      
      this.legend.typeList = this.legend.typeList.map((item, index) => {
        item.value = list[index];
        return item;
      });
      this.initOption();
      this.resestList();
    },
    initOption() {
      const stations = this.list.map(i => i.position_name);
      const yData = Array.from(new Set(stations)).reverse();
      let endDay = this.$moment(this.searchForm.month_str).endOf('months').format('DD');
      const xData = [];
      for(let i = 1; i < Number(endDay) + 1; i++){
        xData.push(i);
      }
      let serieData = [];
        xData.forEach((x, index) => {
          const data = [];
          yData.forEach(y => {
            const item = this.list.find(i => {
              return Number(this.$moment(i.update_time).format('DD')) === x && i.position_name === y;
            });
            data.push(item ? item : {});
          });
        if (data.length > 0) {
          data.forEach((d, index1) => {
            serieData.push([index, index1, d[this.legend.typeId]]);
          });
        } else {
          for (let index1 = 0; index1 < 21; index1++) {
            serieData.push([index, index1, 0]);
          }
        }
      });
      let pieces = [];
      const typeValues = this.levelValues[this.legend.typeId];
      typeValues.forEach((val, index) => {
        const str = {
          max: val + 0.000001,
          color: this.colors[this.levels[index]]
        };
        if (index === 0) {
          str.min = 0.000001;
          str.label = `≤ ${val}`;
        } else {
          str.min = typeValues[index - 1] + 0.000001;
          str.label = `${typeValues[index - 1]} - ${val}`;
        }
        pieces.push(str);
        if (index === typeValues.length - 1) {
          pieces.push({
            min: val,
            label: '＞' + `${val}`,
            color: this.colors.严重污染
          });
        }
      });
      

      const title = this.legend.typeId === 'aqi' ? '月空气质量指数' : '月空气质量分指数';
      
      this.option = {
        title: {
          top: '20',
          text: city + this.searchForm.month_str + title + '(' + this.legend.type + ')日历',
          x: 'center',
          textStyle: {
            fontSize: 24,
            fontFamily: 'AlibabaPuHuiTi-Bold',
            color: '#000',
          },
        },
        grid: {
          top: '80',
          left: '60',
          right: '30',
          bottom: '20',
          containLabel: true,
        },
        tooltip: {
          position: 'top',
          confine: true,
          formatter: (params) => {
            if (params.data[2] === 0) {
              return;
            }
            const dd = params.data[0] + 1 > 10 ? `${params.data[0] + 1}` : '0' + `${params.data[0] + 1}`;
            let arr = this.getTips(dd, yData[params.data[1]]);
            let html = '';
            arr.forEach(m => {
              html += `<div>${m.label}：${m.value}</div>`;
            });
            return html;
          }
        },
        xAxis: {
          type: 'category',
          position: 'top',
          data: xData,
          splitArea: {
            show: true
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: true,
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 16,
          },
        },
        yAxis: {
          name: '站点/日期',
          nameGap: 8,
          nameTextStyle: {
            align: 'right',
            fontFamily: 'AlibabaPuHuiTi-Bold',
            color: '#000',
            fontSize: 16,
          },
          type: 'category',
          data: yData,
          splitArea: {
            show: true
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: true,
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 16,
          },
        },
        visualMap: {
          show: false,
          type: 'piecewise',
          inverse: true,
          precision: 6,
          right: this.legend.typeId === 'co' ? 50 : 40,
          realtime: false,
          calculable: true,
          align: 'left',
          itemWidth: 12,
          itemHeight: 14,
          textStyle: {
            fontSize: 14,
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000'
          },
          // y: 'bottom',
          bottom: '20',
          pieces
        },
        series: [
          {
            name: '空气质量',
            type: 'heatmap',
            data: serieData,
            label: {
              show: true,
              fontFamily: 'AlibabaPuHuiTi-Bold',
              color: '#000',
              fontSize: 14,
              formatter: (params) => {
                return params.value[2] > 0 ? params.value[2] : '';
              }
            },
            itemStyle: {
              borderWidth: 1,
              borderColor: '#000',
              noraml: {
                borderWidth: 1,
              },
              // color: (params) => {
              //   return params.value[2] > 0 ? params.color : 'rgba(0,0,0,0)';
              // },
            },
          }
        ]
      };
    },
    getTips(day,name){
      let list = [
        {name: 'position_name', label: '站点', value: null},
        {name: 'primary_pollutant', label: '首页污染物', value: null},
        {name: 'quality', label: '空气质量', value: null},
        {name: 'aqi', label: 'AQI', value: null},
        {name: 'pm25', label: 'PM₂.₅', value: null},
        {name: 'pm10', label: 'PM₁₀', value: null},
        {name: 'so2', label: 'SO₂', value: null},
        {name: 'no2', label: 'NO₂', value: null},
        {name: 'co', label: 'CO', value: null},
        {name: 'o3_8h', label: 'O₃_8h', value: null},
      ];
      let obj = this.list.find(item => item.update_time == this.$moment(this.searchForm.month_str + '-' + day).format('YYYY-MM-DD') && item.position_name == name);
      if(obj){
        for(let key in obj){
          list.forEach((item,index) => {
            if(item.name == key){
              list[index].value = obj[key];
            }
          })
        }
      }
      return list;
    },
    getQuality(val){
      let data = this.legend.list[this.legend.index].values;
      let name = '优';
      if(val <= data[1]){
        name = '优';
      }else if( val > data[1] && val <= data[2]){
        name = '良';
      }else if( val > data[2] && val <= data[3]){
        name = '轻度污染';
      }else if( val > data[3] && val <= data[4]){
        name = '中度污染';
      }else if( val > data[4] && val <= data[5]){
        name = '重度污染';
      }else if( val > data[5]){
        name = '严重污染';
      }
      return name;
    },
    resestList(){
      this.list = this.list.map(item => {
        item.quality = this.getQuality(item[this.legend.typeId]);
        return item;
      });
    },
    getTotal(name){
      let arr = this.list.filter(item => item.quality == name);
      return arr.length;
    },
  }
}
</script>